<script setup>
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import logo_img from "../assets/images/index/logo.svg"
import success_img from "../assets/images/index/success.svg"
const router = useRouter()

const register = { type: ref(0), email: ref(''), password: ref(''), password_repeat: ref(''), phone: ref(''), captcha: ref(''), nickName: ref(''), name: ref(''), school: ref(''), college: ref(''), number: ref('') }

const types = [{ title: '学生', number: 1 }, { title: '老师', number: 2 }, { title: '专业管理员', number: 3 }, { title: '院级管理员', number: 4 }, { title: '校级管理员', number: 5 }]

const isSchoolInputed = ref(false)


const isNextStep = ref(false)

// const schools = [{ title: '广东外语外贸大学', college: ['信息学院', '数理学院'] }, { title: '华南师范大学', college: ['地理科学学院', '音乐学院'] }, { title: '广东工业大学', college: ['土工学院', '通信工程学院'] }]

const validationButton = { cursor: ref('pointer'), content: ref('获取验证码'), isDisabled: ref(false) }

// image_folder_url
const image_folder_url = "/src/assets/images/index/"

// Success
const isRegistered = ref(false)

// Modal Box
const isOpen = ref(false)
const modal_body = ref('')

// Form logic
watch(register.school, (newValue, oldValue) => {
    if (newValue !== '') {
        isSchoolInputed.value = true
    } else {
        isSchoolInputed.value = false
        register.college.value = ''
    }
})

// validation and nextStep
function nextStep() {
    isNextStep.value = true
}

function backStep() {
    isNextStep.value = false
}

// route to login
function goToLogin() {
    router.push('/login')
}

function getVerificationCode() {
    // validation
    if (register.email.value == '') {
        modal_body.value = '邮箱不能为空';
        openModalBox();
        return;
    }

    const host = "http://api.linwine.space/api/sjk"
    const api = "/login/verify/mail"
    const body = {
        type: 1,
        mail: register.email.value
    }
    const config = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
    }
    fetch(host + api, config)
        .then((res) => res.json())
        .then((data) => {
            if (data && data.code == 200) {
                validationButton.isDisabled.value = true
                validationButton.cursor.value = "not-allowed"
                // timer
                let time = 30;
                const id = setInterval(() => {
                    if (time >= 0) {

                        validationButton.content.value = `重新获取验证码（${time}）`;
                        time--;
                    }
                }, 1000)
                setTimeout(() => {
                    clearInterval(id)
                    validationButton.content.value = "获取验证码"
                    validationButton.isDisabled.value = false
                    validationButton.cursor.value = "pointer"
                }
                    , 30000)
            } else {
                modal_body.value = '获取验证码失败';
            openModalBox();
            }
        })
        .catch((err) => {
            modal_body.value = '请求失败';
            openModalBox();
        })


}

function signUp() {

    // validation
    for (const property in register) {
        if (register[property].value == '' || register[property].value == 0) {
            modal_body.value = '表单不能为空';
            openModalBox();
            return;
        }
    }
    if (register.password.value != register.password_repeat.value) {
        modal_body.value = '两次密码需要保持一致';
        openModalBox();
        return;
    }

    // register
    const host = "http://api.linwine.space/api/sjk"
    const api = "/login/register"
    const body = {}
    Object.keys(register).filter(v => v != 'password_repeat').forEach(v => {
        body[v] = register[v].value
    })
    const config = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
    }

    fetch(host+api, config)
        .then(res => res.json())
        .then(data => {
            if (data && data.code == 200) {
                isRegistered.value = true
            } else {
                modal_body.value = '注册失败';
            openModalBox();
            }
        })
        .catch(err => {
            modal_body.value = '请求失败';
            openModalBox();
        })

}


// Modal Logic

function openModalBox() {
    isOpen.value = true
}

function closeModalBox() {
    isOpen.value = false
}


</script>

<template   >
    <form v-if="!isRegistered">
        <div class="form-header" >
            <img :src="logo_img" alt="Logo"  width="207" />
        </div>
        <div class="container" v-show="!isNextStep">

            <div>

                <select id="type" v-model="register.type.value" style="width: 180px;">
                    <option disabled value="0">请选择身份</option>
                    <option v-for="(type, index) in types" :key="index" :value="type.number">{{ type.title }}</option>
                </select>
            </div>


            <!-- <label for="nickName"><b>昵称</b></label> -->
            <input type="text" id="nickName" placeholder="昵称" required v-model="register.nickName.value" />

            <!-- <label for="name"><b>真实姓名</b></label> -->
            <input type="text" placeholder="真实姓名" id="name" required v-model="register.name.value" />

            <!-- <label for="school"><b>学校</b></label> -->
            <input type="text" placeholder="学校名称" id="school" required v-model="register.school.value" />
            <!-- <select id="school" v-model="register.school.value">
                <option disabled value="">请选择学校</option>
                <option v-for="(school, index) in schools" :key="index">{{ school.title }}</option>
            </select> -->

            <!-- <label for="school"><b>学院</b></label> -->
            <input type="text" placeholder="学院名称" id="college" required v-model="register.college.value" :disabled="!isSchoolInputed" />

            <!-- <select id="college" v-model="register.college.value">
                <option disabled value="">请选择学院</option>
                <template v-if="isSchoolSelected">

                    <option v-for="(college, index) in selectedSchool.college" :key="index">{{ college }}</option>
                </template>
            </select> -->


            <!-- <label for="number"><b>学号/教工号</b></label> -->
            <input type="text" id="number" placeholder="学号/教工号" required v-model="register.number.value" />

            <div class="footer-container">
                <button type="button" class="btn" style="width: 50%; " @click="nextStep">下一步</button>
                <span @click="goToLogin" >使用已有账户登录</span>
            </div>


        </div>
        <div class="container" v-show="isNextStep">
            <!-- <label for="email"><b>邮箱</b></label> -->
            <input type="text" id="email" placeholder="邮箱" required v-model="register.email.value" />

            <div class="verification-container">
                <input type="text" id="captcha" placeholder="验证码" required v-model="register.captcha.value" style="width: 30%; margin: 0;" />
                <button type="button" class="btn" style="width: 60%;" :style="{ cursor: validationButton.cursor.value }"
                    @click="getVerificationCode" :disabled="validationButton.isDisabled.value" >{{ validationButton.content.value }}</button>
            </div>
            <!-- <label for="password"><b>密码</b></label> -->
            <input type="password" placeholder="密码" id="password" required v-model="register.password.value" />

            <!-- <label for="password_repeat"><b>再次确认密码</b></label> -->
            <input type="password" placeholder="确认密码" id="password_repeat" required
                v-model="register.password_repeat.value" />

            <!-- <label for="phone"><b>手机号码</b></label> -->
            <input type="text" id="phone" placeholder="手机号码" required v-model="register.phone.value" />


            <div class="footer-container">
                <button type="button" class="btn" style="width: 40%;" @click="backStep">上一步</button>
                <button type="button" class="btn" style="width: 40%;" @click="signUp">注册</button>
            </div>


        </div>

    </form>
    <div class="success-container" v-if="isRegistered" >
                <header class="success-header">
                    <img :src="success_img" alt="Success Register"   />
                </header>
                <main class="success-content">
                    <span>您的账号: {{ register.email.value }}注册成功!</span>
                </main>
                <footer class="success-footer">

                    <!-- <button type="button" class="btn" style="width: 40%;">进入系统</button> -->
                </footer>
            </div>
    
    <div class="modal" :class="{ active: isOpen }">
        <div class="modal-content">
            <div class="modal-header">
                <span>提醒</span>
                <span class="close" @click="closeModalBox">&times;</span>
            </div>

            <div class="modal-body">{{ modal_body }}</div>
            <div class="modal-footer">感谢使用</div>
        </div>

    </div>
</template>


<style scoped>

*, ::before, ::after {
    box-sizing: border-box;
    margin: 0;
}
form, .success-container {
    width: 660px;
    padding: 28px 90px 46px 90px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    background-color: #fff;
    z-index: 1;
}

.form-header {
    text-align: center;
    margin: 18px 0 18px 0;
}


input[type=text],
input[type=password] {
    width: 100%;
    padding: 9px 17px 11px 17px;
    margin: 5px 0 5px 0;
    display: inline-block;
    border: none;
    background-color: #f1f2f6;
    border-radius: 10px;
    height: 36px;
    font-size: 16px;
    font-family: Source Han Sans CN;
    
}

input[type=text]::placeholder,
input[type=password]::placeholder {
    font-size: 16px;
    font-family: Source Han Sans CN;
    color: #707070;
    opacity: 0.7;
}

input[type=text]:focus,
input[type=password]:focus {
    background-color: #ddd;
    outline: none;
}

#college:disabled {
    cursor: not-allowed;
}

.container select {
    width: 100%;
    border: none;
    padding: 7px 17px 8px 17px;
    margin: 5px 0 5px 0;
    background-color: #f1f2f6;
    display: inline-block;
    outline: none;
    border-radius: 10px;
    height: 36px;
    font-size: 16px;
    font-family: Source Han Sans CN;
}

.verification-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 5px 0 5px 0;
}

.btn {
    width: 100%;
    cursor: pointer;
    padding: 0;
    border: none;
    border-radius: 10px;
    background-color: #8493a6;
    color: #F5F5F5;
    height: 36px;
    line-height: 40px;
    font-size: 18px;
    font-family: Source Han Sans CN;
    letter-spacing: 2px;
    opacity: 0.85;
}


.btn:hover {
    opacity: 1;
}

.btn:active {
    transform: translateY(2px);
}

/* success Part */
.success-header,
.success-content,
.success-footer {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px 0;
}

.success-content span {
    width: 80%;
    text-align: center;
    font-size: 16px;
    color: #707070;
}

.footer-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 5px 0 5px 0;
}

.footer-container span {
    color: #8493a6;
    width: 40%;
    text-align: center;
    height: 36px;
    line-height: 36px;
    font-size: 16px;
    font-family: Source Han Sans CN;
    letter-spacing: 2px;
    display: inline-block;
    cursor: pointer;
}


/*  Modal Box */
.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.2);
    padding-top: 10px;
}

.modal-content {
    position: relative;
    background-color: white;
    margin: 0 auto;
    margin-top: 65px;
    width: 576px;
    top: 0;
    animation-name: animatetop;
    animation-duration: 0.2s;
    animation-fill-mode: forwards;
}

@keyframes animatetop {
    from {
        top: -300px;
        opacity: 0
    }

    to {
        top: 0;
        opacity: 1
    }
}

.modal-header {
    padding: 10px 16px;
    background-color: #8493a6;
    font-size: 25px;
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: baseline;
}

.modal-body {
    padding: 10px 16px;
}

.modal-footer {
    padding: 10px 16px;
    background-color: #8493a6;
    color: white;
    font-size: 25px;
}


.active {
    display: block;
}

.close {
    cursor: pointer;

}

.close:hover {
    color: black;
}
</style>